import React, { useEffect, useState } from "react";
import { Button, Col, Row, Space, Table, Tag, Modal, Switch } from "antd";
import type { ColumnsType } from "antd/es/table";
import CategoryForm from "./components/category-form";
import { categoryGet } from "@/api/course";
import { CategoryType } from "@/types/course";

const columns: ColumnsType<CategoryType> = [
  {
    title: "分类ID",
    dataIndex: "objectId",
    key: "objectId",
    render: (id) => <a>{id}</a>,
  },
  {
    title: "分类名称",
    dataIndex: "name",
    key: "name",
  },
  {
    title: "是否上架",
    dataIndex: "isonline",
    key: "isonline",
    render: (bool) => {
      return <Switch checked={bool} />;
    },
  },
  {
    title: "操作",
    key: "action",
    render: (_, record) => (
      <Space size="middle">
        <Button type="primary" size="small">
          编辑
        </Button>
        <Button type="primary" size="small" danger>
          删除
        </Button>
      </Space>
    ),
  },
];

// const data: DataType[] = [
//   {
//     key: "1",
//     name: "John Brown",
//     age: 32,
//     address: "New York No. 1 Lake Park",
//     tags: ["nice", "developer"],
//   },
//   {
//     key: "2",
//     name: "Jim Green",
//     age: 42,
//     address: "London No. 1 Lake Park",
//     tags: ["loser"],
//   },
//   {
//     key: "3",
//     name: "Joe Black",
//     age: 32,
//     address: "Sydney No. 1 Lake Park",
//     tags: ["cool", "teacher"],
//   },
// ];

const CateList: React.FC = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [data, setData] = useState<Array<CategoryType>>([]);
  useEffect(() => {
    categoryGet(true).then((res) => {
      console.log(res);
      let results: CategoryType[] = res.data.results;
      let parentArr = results.filter((item) => item.parentId == "0-0");
      parentArr.forEach((item) => {
        let children = results.filter(
          (child) => item.objectId == child.parentId
        );
        if (children.length) {
          item.children = children;
        }
      });
      setData(parentArr);
    });
  }, []);
  const showModal = () => {
    setIsModalOpen(true);
  };

  const handleOk = () => {
    setIsModalOpen(false);
  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };
  return (
    <>
      <Row justify="space-between">
        <Col>课程分了管理</Col>
        <Col>
          <Button type="primary" onClick={showModal}>
            新增分类
          </Button>
        </Col>
      </Row>
      <Modal
        title="Basic Modal"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
        footer={null}
      >
        <CategoryForm cateData={data} />
      </Modal>
      <Table columns={columns} dataSource={data} rowKey="objectId" />;
    </>
  );
};

export default CateList;
